﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL.Repositories
{
    public class BookingRepository : RepositoryInterfaces.IBookingRepository
    {

        /// <summary>
        /// Save a booking to db
        /// </summary>
        /// <param name="booking">The booking object to save</param>
        /// <exception cref="InvalidOperationException">Failed to save to db</exception>
        /// <exception cref="Exception">Other exceptions</exception>
        public void SaveBooking(Booking booking)
        {
            try
            {
                using (BalderEntities _db = new BalderEntities()) // creates a scope with savechanges itself
                {
                    // attach already existing objects to new object
                    _db.Users.Attach(booking.User);
                    _db.ScreenCasts.Attach(booking.ScreenCast);
                    foreach (var item in booking.PartBookings)
                    {
                        _db.ScreenCast_Seat.Attach(item.ScreenCast_Seat);
                    }

                    // add new objects (also adds part bookings to db)
                    _db.Bookings.Add(booking);
                    _db.SaveChanges();
                }
            }
            catch (InvalidOperationException e)
            {
                throw new InvalidOperationException("Failed to save to db" + Environment.NewLine + e.Message);
            }
            catch (Exception)
            {
                throw;
            }
        }
    }
}
